import { IItemConfig } from "../../../Script/Base/BaseConfig";
import BaseView from "../../../Script/Base/BaseView";
import { EBundleType, EResType, EViewType } from "../../../Script/Common/Enum";
import { GlobalData } from "../../../Script/Common/GlobalData";
import { IBagItemData, IFlyResData, IGameData, ITalkData, IViewData } from "../../../Script/Interface/IMessage";
import { SceneGame } from "../../../Script/SceneGame";
import AppService from "../../../Script/Service/AppService";
import GameUtil from "../../../Script/Util/GameUtil";
import StorageUtil from "../../../Script/Util/StorageUtil";
import EventID from "../../Common/EventID";
import Message from "../../Common/Message";
import TaskModule from "../../Common/TaskModule";
import { AdManager } from "../../naodong/ads/AdManager";
import TownUI from "../town/TownUI";
import MarketGuest from "./MarketGuest";
import MarketItem from "./MarketItem";

const { ccclass, property } = cc._decorator;

export interface IMarketItem {
    id: number;
    itemId: number;
    name: string;
    num: number;
    sale: number;
}

const VIEW_DATA: IViewData = {
    name: 'MarketUI',
    type: EViewType.Panel,
    bundle: EBundleType.Game,
    zIndex: 100,
};

@ccclass
export default class MarketUI extends BaseView {
    public static instance: MarketUI = null;

    @property({ type: cc.Node, tooltip: "背包弹窗" })
    public bag: cc.Node = null;

    @property({ type: cc.Node, tooltip: "引导节点(layout无法聚焦到固定点, 用空节点当坐标用)" })
    public rect: cc.Node = null;

    @property({ type: cc.Node, tooltip: "摊位item" })
    private item: cc.Node = null;
    @property({ type: cc.Node, tooltip: "摊位父节点" })
    private items: cc.Node = null;

    @property({ type: cc.Node, tooltip: "顾客" })
    private itemGuest: cc.Node = null;
    @property({ type: cc.Node, tooltip: "顾客父节点" })
    private guests: cc.Node = null;

    @property({ type: cc.Node, tooltip: "飞icon节点" })
    public flyIcons: cc.Node = null;

    public guestCount: number = 0;
    public clickStallId: number = -1;
    // private doubleTime: number = 5 * 60 * 1000;
    // private recordTime: number = 0;
    // public ratio: number = 1;
    public addCount: number = 0;

    /** 摊位数据 */
    private stallDatas: IMarketItem[] = [];

    private gameData: IGameData = null;
    private talkData: ITalkData = null;

    protected onLoad() {
        super.onLoad();
        MarketUI.instance = this;

        this.gameData = StorageUtil.instance.getGameData();
        this.talkData = StorageUtil.instance.getTalkData();

        this.initStalls();
        this.initGuest();
        this.initBag();
    }

    private initStalls() {
        this.stallDatas = [];
        for (let i = 0; i < 6; i++) {
            const data = { id: i + 1, itemId: -1, name: '', num: 0, sale: 0 };
            this.stallDatas.push(data);
        }

        for (let i = 0; i < this.stallDatas.length; i++) {
            const item = cc.instantiate(this.item);
            item.parent = this.items;
            item.setPosition(cc.v2(0, 0));
            item.getComponent(MarketItem).setData(this.stallDatas[i]);
        }

        // 引导摊位高亮
        if (this.talkData.id === 10305) {
            SceneGame.instance.showGuideUI(this.rect, 0.8);
        }
    }

    private initGuest() {
        cc.tween(this.node).repeatForever(
            cc.sequence(
                cc.callFunc(() => {
                    this.createGuest();
                }),
                cc.delayTime(1),
            ),
        ).start();
    }

    private initBag() {
        this.bag.active = false;
    }

    public getGuestNeedData() {
        const has: IMarketItem[] = [];
        this.stallDatas.forEach((o) => {
            if (o.itemId > -1 && o.num > 0) {
                has.push(o);
            }
        });

        const data = has[Math.floor(Math.random() * has.length)];
        return data;
    }

    public createGuest() {
        if (this.guestCount < 3) {
            const item = cc.instantiate(this.itemGuest);
            item.parent = this.guests;
            item.getComponent(MarketGuest).come();
            this.guestCount++;
        }
    }

    public refreshStallSales() {
        this.items.children.forEach((o, i)=> {
            o.getComponent(MarketItem).refresh();
        });
    }

    public refreshStall(itemId: number) {
        const data = this.stallDatas.find((o) => o.itemId === itemId);
        if (data) {
            data.num--;
            if (data.num <= 0) {
                data.itemId = -1;
                data.name = '';
                data.num = 0;
                data.sale = 0;
            }
            // 获取节点
            const item = this.items.children[data.id - 1];
            item.getComponent(MarketItem).setData(data);

            // 卖的是顾母首饰
            if (this.talkData.id === 10305) {
                if (itemId === 10000) {
                    // 设置为town和疯老头对话
                    this.talkData.id = 10307;
                    // 更新任务数据
                    TaskModule.instance.saveData();
                }
            }
        }
    }

    public refreshBag(itemConfig: IItemConfig, itemData: IBagItemData) {
        if (this.clickStallId != -1) {
            const index = this.clickStallId - 1;
            const id = this.stallDatas[index].id;
            this.stallDatas[index] = {
                id: id,
                itemId: itemData.id,
                name: itemConfig.name,
                num: itemData.num,
                sale: itemConfig.basePrice
            };
            this.items.children[index].getComponent(MarketItem).setData(this.stallDatas[index]);
            this.clickStallId = -1;
        }
    }

    public showBagViewAnim() {
        SceneGame.instance.hideGuideUI();
        this.isHasChild = true;
        this.bag.active = true;
        const mask = cc.find("mask", this.bag);
        const root = cc.find("root", this.bag);
        if (mask) {
            mask.opacity = 0;
            cc.tween(mask).to(0.3, { opacity: GlobalData.maskOpacity }).start();
        }

        if (root) {
            root.scale = 0;
            cc.tween(root).to(0.3, { scale: 1, opacity: 255 }, cc.easeBackOut()).call(() => {
                // 引导手镯高亮
                if (this.talkData.id === 10305) {
                    Message.instance.send(EventID.BAG_LIGHT_ITEM, { id: 10000 });
                }
            }).start();
        }
    }

    public hideBagViewAnim() {
        SceneGame.instance.hideGuideUI();
        const mask = cc.find("mask", this.bag);
        const root = cc.find("root", this.bag);
        if (mask) {
            cc.tween(mask).to(0.3, { opacity: 50 }).start();
        }

        if (root) {
            cc.tween(root).sequence(
                cc.spawn(
                    cc.scaleTo(0.3, 0.4).easing(cc.easeBackIn()),
                    cc.fadeOut(0.3),
                ),
                cc.callFunc(() => {
                    this.isHasChild = false;
                    this.bag.active = false;
                }),
            ).start();
        }
    }

    public onCloseChild() {
        this.isHasChild = false;
        this.bag.active = false;
    }

    public onCloseClicked() {
        super.onCloseClicked();
        TownUI.instance.check();
    }

    private onBtnsClicked(event: cc.Event.EventTouch, eventData: string) {
        const name = event.target.name;
        switch (name) {
            case "btnCloseBag":
                {
                    this.hideBagViewAnim();
                }
                break;
            case "btnAdd":
                {
                    // 播放视频
                    AdManager.showVideoAd(() => {
                        this.addCount++;
                        this.refreshStallSales();
                    });
                }
                break;
            case "btnAllSale":
                {
                    // 播放视频
                    AdManager.showVideoAd(() => {
                        let money = 0;
                        this.stallDatas.forEach((o) => {
                            if (o && o.num > 0) {
                                // 卖出金额 = 数量 * (基础金额 + 基础金额 / 2 * 加价次数)
                                money += o.num * (o.sale + o.sale / 2 * this.addCount);
                                o.num = 0;
                                this.refreshStall(o.itemId);
                            }
                        });

                        if (money > 0) {
                            const data = SceneGame.instance.getFlyResData();
                            const flyData: IFlyResData = {
                                resType: EResType.Money,
                                parent: data.flyNode,
                                from: this.flyIcons,
                                to: data.money,
                                value: Math.ceil(money),
                                flyTimes: 20,
                                maxWidth: 60,
                                maxHeight: 60
                            }
                            GameUtil.instance.flyResIcon(flyData);
                        }
                    });
                }
                break;
        }
    }
}
AppService.instance.registViewData(VIEW_DATA);